Creating and Initializing Arrays

Arrays are used to store ordered collections of values. You can create an array in JavaScript using array literals or the Array constructor.

Array Literals

let fruits = ['apple', 'banana', 'orange'];
let mixed = [1, true, 'hello', null];

Array Constructor

let numbers = new Array(1, 2, 3, 4, 5);
let empty = new Array(3); // [empty x 3]

 

Array Methods

JavaScript provides various built-in methods to manipulate arrays.

Adding and Removing Elements

  • push(): Adds one or more elements to the end of the array.
  • pop(): Removes the last element from the array.
  • unshift(): Adds one or more elements to the beginning of the array.
  • shift(): Removes the first element from the array.
  • splice(): Adds or removes elements from an array.

Array Iteration

  • forEach(): Executes a provided function once for each array element.
  • map(): Creates a new array with the results of calling a provided function on every element.
  • filter(): Creates a new array with all elements that pass the test implemented by the provided function.
  • reduce(): Applies a function against an accumulator and each element to reduce it to a single value.

Other Useful Methods

  • concat(): Merges two or more arrays and returns a new array.
  • slice(): Returns a shallow copy of a portion of an array.
  • indexOf(): Returns the first index at which a given element can be found in the array.
  • includes(): Determines whether an array includes a certain value.
  • reverse(): Reverses the order of the elements in the array.
  • sort(): Sorts the elements of an array in place.

Spread and Rest Operators

The spread operator (...) allows you to spread the elements of an iterable (like an array) into individual elements, while the rest operator collects multiple elements into an array.

const fruits = ['apple', 'banana', 'orange'];
const otherFruits = ['pear', 'grape'];
const allFruits = [...fruits, ...otherFruits]; // ['apple', 'banana', 'orange', 'pear', 'grape']
const [first, ...rest] = allFruits;
console.log(first); // 'apple'
console.log(rest); // ['banana', 'orange', 'pear', 'grape']

In the next chapter, we'll explore objects, which are another essential data structure in JavaScript.